import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store/index'
const routes = [

  // 登陆
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/menus',//vue3基本语法演示
    name: 'menus',
    redirect:'/profile',
    component: () => import('../views/menus.vue'),
    children: [
      {
        path: '/profile',
        name: 'profile',
        component: () => import('../views/profile.vue'),
      },
      {
        path: '/chart',
        name: 'chart',
        component: () => import('../views/chart.vue'),
      },
      {
        path: '/manage',
        name: 'manage',
        component: () => import('../views/user/manage.vue'),
      },
      {
        path: '/role',
        name: 'role',
        component: () => import('../views/user/role.vue'),
      },
      {
        path: '/permission',
        name: 'permission',
        component: () => import('../views/user/permission.vue'),
      },
      {
        path: '/ranking',
        name: 'ranking',
        component: () => import('../views/article/ranking.vue'),
      },
      {
        path: '/create',
        name: 'create',
        component: () => import('../views/article/create.vue'),
      },
      {
        path: '/import',
        name: 'import',
        component: () => import('../views/user/import.vue'),
      },
    ]
  },
  //根目录,到登录页面
  {
    path: '/',
    redirect: '/login'
  },
  //找不到页面到404,！！注意vue3里不能用*
  {
    path: '/:catchAll(.*)',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = store.state.userInfo
  const islogin = to.path === "/login"
  if (islogin && token) {
    console.log(111);
    return next('menus')
  }
  if (!islogin && !token) {
    console.log(222);
    return next('login')
  }
  next()
})

// router.beforeEach((to,from,next)=>{
//   const token=store.getters.token;
//   const isLogin=to.name==='login';
//   // 如果有token，并且是在登录页，那么跳转到首页
//   if(token && isLogin){
//         return next({name:'HomeLayout'});
//   }
//   // 如果没有token，并不是在登录页，跳转到登录页
//   if(!token && !isLogin){
//       return next({name:'login'});
//   }
//   next();
// })

export default router
